<template>
  <el-form
    ref="userForm"
    :model="userInfo"
    label-width="120px"
    style="margin-left: 120px; margin-top: 30px"
    :rules="rules"
  >
    <el-form-item label="姓名:" prop="username">
      <el-input v-model="userInfo.username" style="width:300px" />
    </el-form-item>
    <el-form-item label="密码:" prop="password">
      <el-input v-model="userInfo.password" type="password" style="width:300px" />
    </el-form-item>

    <el-form-item>
      <el-button type="primary" @click="update">更新</el-button>
    </el-form-item>
  </el-form>
</template>
<script>
import { getUserByID, saveUserDetailById } from '@/api/user'
export default {
  data() {
    return {
      userInfo: {
        username: '',
        password: ''
      },
      rules: {
        username: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
        password: [{ required: true, message: '密码不能为空', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.setEmployeesInfo()
  },
  methods: {
    async setEmployeesInfo() {
      try {
        const res = await getUserByID(this.$route.query.id)
        // console.log('getUserByID', res)
        this.userInfo = res.data.data
        // 保存数据
      } catch (err) {
        console.log('getUserByID', err)
      }
    },
    // 更新按钮
    update() {
      this.$refs.userForm.validate(async(valid) => {
        if (!valid) return // 如果表单验证不通过，直接return
        // 通过的代码
        try {
          // console.log('验证成功')
          await saveUserDetailById(this.userInfo)
          this.$message.success('更新成功')
          // this.setEmployeesInfo()
          this.$router.back()
        } catch (error) {
          console.log(error)
        }
      })
    }
  }
}
</script>

